package com.test.personalblogproject.controller;


import com.github.pagehelper.page.PageParams;
import com.test.personalblogproject.mapper.UserMapper;
import com.test.personalblogproject.pojo.*;
import com.test.personalblogproject.service.ArticleService;
import com.test.personalblogproject.service.UserService;
import com.test.personalblogproject.utils.ThreadLocalUtil;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/articles")
public class ArticleController {
    @Autowired
    private ArticleService ArticleService;
    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;

    @PostMapping("/publish")
    //  @RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)；
    //  而最常用的使用请求体传参的无疑是POST请求了，所以使用@RequestBody接收数据时，一般都用POST方式进行提交。
    public Result publish(@RequestBody ArticleParam articleParam){
        return ArticleService.publish(articleParam);
    }
    @PostMapping("listByAuthorId")
    public Result FindArticlesByAuthorId(Long authorId){
        return ArticleService.FindArticlesByAuthorId(authorId);

    }
    //删除文章
    @DeleteMapping("delete/{id}")
    public Result deleteById(@PathVariable Long id) {
        return ArticleService.deleteById(id);
    }
    //修改文章
    @PostMapping("updatearticle")
    public  Result updateByarticleId(@RequestBody ArticleParam articleParam){
        return Result.success(ArticleService.updateByarticleId(articleParam));
    }

    //点赞/取消点赞
    @PostMapping("/like")
    public Result like(@RequestBody LikeParam param) {
        // 从登录上下文拿用户ID，这里简化
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        System.out.println(username);
        User loginUser = userService.findByUserName(username);
        System.out.println(loginUser);
        if(loginUser == null){
            throw new RuntimeException("用户不存在");
        }
        int loginUserId = loginUser.getId();
        boolean status = articleService.toggleLike(loginUserId, param.getArticleId());
        if (!status) {
            return Result.success("取消点赞");
        }
        return Result.success("点赞成功");
    }

    //获取当前用户点赞过的文章 id 列表
    @GetMapping("/likeList")
    public Result myLikeIds() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        int loginUserId = loginUser.getId();
        return Result.success(articleService.likedArticleIds(loginUserId));
    }

    //获取文章点赞数
    @GetMapping("/likeCount/{articleId}")
    public Result likeCount(@PathVariable int articleId) {
        return Result.success(articleService.countLikes(articleId));
    }
}
